<template>
  <div class="couponym">
    <a-tabs defaultActiveKey="1" @change="callback">
      <a-tab-pane tab="优惠券设置" key="1">
        <div class="yhsz_box">
          <div class="addyhj">
            <a-button type="primary" @click="showDrawer">添加优惠券</a-button>
          </div>
          <a-drawer
            title="添加优惠券"
            :width="720"
            @close="onClose"
            :visible="visible"
            :bodyStyle="{paddingBottom: '80px'}"
          >
            <a-form :form="form" layout="vertical" hideRequiredMark>
              <a-row :gutter="16">
                <a-col :span="12" class="colmar">
                  <a-form-item label="面额"></a-form-item>
                  <a-input
                    v-decorator="['price', {
                  rules: [{ required: true, message: '请输入优惠券面额' }]
                }]"
                    v-model="price"
                    placeholder="请输入优惠券面额"
                  />
                </a-col>
                <a-col :span="12" class="colmar">
                  <a-form-item label="满使用"></a-form-item>

                  <a-input
                    v-decorator="['full_price', {
                  rules: [{ required: true, message: '请输入满使用面额' }]
                }]"
                    v-model="full_price"
                    placeholder="请输入满使用面额"
                  />
                </a-col>
              </a-row>
              <a-row :gutter="16">
                <a-col :span="12" class="colmar">
                  <a-form-item label="开始日期"></a-form-item>
                  <a-date-picker style="width:328px" placeholder="请选择开始日期" @change="startChange" />

                  <!--  @change="endChange" :defaultValue="moment(record.end_time,'YYYY-MM-DD')" -->
                </a-col>
                <a-col :span="12" class="colmar">
                  <a-form-item label="失效日期"></a-form-item>
                  <a-date-picker style="width:328px" placeholder="请选择失效日期" @change="endChange" />
                </a-col>
              </a-row>
              <a-row :gutter="16">
                <a-col :span="12" class="colmar">
                  <a-form-item label="限领次数"></a-form-item>
                  <a-input
                    v-model="limit_times"
                    v-decorator="['limit_times', {
                  rules: [{ required: true, message: '请输入限领次数' }]
                }]"
                    placeholder="请输入限领次数"
                  />
                </a-col>
              </a-row>
            </a-form>
            <div
              :style="{
                position: 'absolute',
                right: 0,
                bottom: 0,
                width: '100%',
                borderTop: '1px solid #e9e9e9',
                padding: '10px 16px',
                background: '#fff',
                textAlign: 'right',
                zIndex: 1,
               }"
            >
              <a-button :style="{marginRight: '8px'}" @click="onClose">取消</a-button>
              <a-button @click="addyhjsub" type="primary">提交</a-button>
            </div>
          </a-drawer>
          <a-table
            :columns="yhszcolumns"
            @change="getyhjlist"
            :dataSource="data"
            bordered
            :pagination="yhszpagination"
          >
            <template
              v-for="col in ['price',  'limit_times', 'full_price']"
              :slot="col"
              slot-scope="text, record, index"
            >
              <div :key="col">
                <a-input
                  v-if="record.editable"
                  style="margin: -5px 0"
                  :value="text"
                  @change="e => handleChange(e.target.value, record.key, col)"
                />
                <template v-else>{{text}}</template>
              </div>
            </template>
            <template
              v-for="startcol in ['start_time']"
              :slot="startcol"
              slot-scope="text, record, index"
            >
              <div :key="startcol">
                <a-date-picker
                  v-if="record.editable"
                  placeholder="请选择开始日期"
                  :defaultValue="moment(record.start_time,'YYYY-MM-DD')"
                  @change="startChange"
                />
                <template v-else>{{text}}</template>
              </div>
            </template>
            <template
              v-for="endcol in ['end_time']"
              :slot="endcol"
              slot-scope="text, record, index"
            >
              <div :key="endcol">
                <a-date-picker
                  placeholder="请选择失效日期"
                  :defaultValue="moment(record.end_time,'YYYY-MM-DD')"
                  v-if="record.editable"
                  @change="endChange"
                />
                <template v-else>{{text}}</template>
              </div>
            </template>
            <template slot="operation" slot-scope="text, record, index">
              <div class="editable-row-operations">
                <span v-show="record.editable">
                  <a class="del" @click="() => save(record,record.key)">保存</a>
                  <a-popconfirm title="确定取消吗?" @confirm="() => cancel(record.key)">
                    <a>取消</a>
                  </a-popconfirm>
                </span>
                <span class="del" v-show="!record.editable">
                  <a @click="() => edit(record.key)">修改</a>
                </span>
                <span class="del" v-show="!record.editable">
                  <a @click="deltel(record.key)">删除</a>
                </span>
                <span class="del" v-show="!record.editable">
                  <a v-show="record.is_open" @click="couponisOpen(record)">关闭</a>
                  <a v-show="!record.is_open" @click="couponisOpen(record)">开启</a>
                </span>
              </div>
            </template>
          </a-table>
        </div>
      </a-tab-pane>
      <a-tab-pane tab="优惠券管理" key="2" forceRender>
        <div class="yhgl_box">
          <a-table
            :columns="yhglcolumns"
            @change="getyhjjgl"
            :pagination="pagination"
            :dataSource="yhgldata"
            bordered
          >
            <template
              v-for="col in ['price', 'start_time', 'end_time', 'limit_times', 'full_price']"
              :slot="col"
              slot-scope="text, record, index"
            >
              <div :key="col">
                <a-input
                  v-if="record.editable"
                  style="margin: -5px 0"
                  :value="text"
                  @change="e => handleChange(e.target.value, record.key, col)"
                />
                <template v-else>{{text}}</template>
              </div>
            </template>
            <template slot="yhj" slot-scope="text, record, index">
              <div class="yhj_box" :class="record.is_expire==1?'timeout':''">
                <p class="mj">满{{record.full_price}}减{{record.price}}优惠券</p>
                <p v-if="record.is_expire==1">{{record.is_used==1&&record.is_expire==1?'已使用':'已过期'}}</p>
                <p v-if="record.is_expire==0">可使用</p>
                <p>截止：{{record.ent_time}}</p>
              </div>
            </template>
            <!-- <template slot="operation" slot-scope="text, record, index">
              <div class="editable-row-operations">
                <span v-show="record.editable">
                  <a class="del" @click="() => save(record.key)">保存</a>
                  <a-popconfirm title="确定取消吗?" @confirm="() => cancel(record.key)">
                    <a>取消</a>
                  </a-popconfirm>
                </span>
                <span class="del" v-show="!record.editable">
                  <a @click="() => edit(record.key)">修改</a>
                </span>
                <span class="del" v-show="!record.editable">
                  <a>删除</a>
                </span>
                <span class="del" v-show="!record.editable">
                  <a>关闭</a>
                </span>
              </div>
            </template>-->
          </a-table>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>

<script>
import qs from "qs";
import moment from "moment";
const yhszcolumns = [
  {
    title: "面额",
    dataIndex: "price",
    scopedSlots: { customRender: "price" }
  },
  {
    title: "开始日期",
    dataIndex: "start_time",
    scopedSlots: { customRender: "start_time" }
  },
  {
    title: "失效日期",
    dataIndex: "end_time",
    scopedSlots: { customRender: "end_time" }
  },
  {
    title: "限领次数",
    dataIndex: "limit_times",
    scopedSlots: { customRender: "limit_times" }
  },
  {
    title: "满使用",
    dataIndex: "full_price",
    scopedSlots: { customRender: "full_price" }
  },
  {
    title: "操作",
    dataIndex: "operation",
    scopedSlots: { customRender: "operation" }
  }
];
const yhglcolumns = [
  {
    title: "会员编号",
    dataIndex: "id_num",
    scopedSlots: { customRender: "id_num" }
  },
  {
    title: "公司名称",
    dataIndex: "gsmc",
    scopedSlots: { customRender: "gsmc" }
  },
  {
    title: "手机号码",
    dataIndex: "phone",
    scopedSlots: { customRender: "phone" }
  },
  {
    title: "姓名",
    dataIndex: "username",
    scopedSlots: { customRender: "username" }
  },
  {
    title: "领取",
    dataIndex: "yhj",
    scopedSlots: { customRender: "yhj" }
  },
  {
    title: "领取时间",
    dataIndex: "dateline",
    scopedSlots: { customRender: "dateline" }
  }
  //   {
  //     title: "操作",
  //     dataIndex: "operation",
  //     scopedSlots: { customRender: "operation" }
  //   }
];

const data = [];
const yhgldata = [];
for (let i = 0; i < 100; i++) {
  // data.push({
  //   key: i.toString(),
  //   money: "5元",
  //   startdate: "2020-3-13",
  //   enddate: "2020-4-13",
  //   limitnum: "5",
  //   fullmoney: "520"
  // });
  // yhgldata.push({
  //   key: i.toString(),
  //   money: "5元",
  //   startdate: "2020-3-13",
  //   enddate: "2020-4-13",
  //   limitnum: "5",
  //   yhj: "520",
  //   lqdate: "2020-3-13"
  // });
}
export default {
  data() {
    this.cacheData = data.map(item => ({ ...item }));
    return {
      moment,
      data,
      yhgldata,
      yhglcolumns,
      yhszcolumns,
      editingKey: "",
      start_time: "",
      end_time: "",
      form: this.$form.createForm(this),
      visible: false,
      price: "", //添加优惠券面额
      full_price: "", //添加满使用面额
      limit_times: "", //添加限领次数
      pagination: {
        defaultPageSize: 10,
        showTotal: total => `共 ${total} 条数据`,
        total: 0
      },
      yhszpagination: {
        defaultPageSize: 10,
        showTotal: total => `共 ${total} 条数据`,
        total: 0
      }
    };
    return {};
  },

  methods: {
    showDrawer() {
      this.visible = true;
    },
    onClose() {
      this.visible = false;
    },
    callback(key) {
      console.log(key);
      if (key == 1) {
        this.getyhjlist(this.yhszpagination);
      } else {
        this.getyhjjgl(this.pagination);
      }
    },
    handleChange(value, key, column) {
      const newData = [...this.data];
      const target = newData.filter(item => key === item.key)[0];
      if (target) {
        target[column] = value;
        this.data = newData;
      }
    },
    deltel(key) {
      this.axios
        .post(
          "huiyuan/couponDelete.php",
          qs.stringify({
            id_num: key
          })
        )
        .then(res => {
          console.log(res);
          if (res.data.code == 303) {
            this.getyhjlist(this.yhszpagination);
            this.$notification["success"]({
              message: "成功",
              description: res.data.msg
            });
          } else {
            this.$notification["error"]({
              message: "失败",
              description: res.data.msg
            });
          }
        });
    },
    edit(key) {
      const newData = [...this.data];
      const target = newData.filter(item => key === item.key)[0];
      if (target) {
        target.editable = true;
        this.data = newData;
      }
    },
    startChange(date, dateString) {
      console.log(date, dateString);
      this.start_time = dateString;
    },
    endChange(date, dateString) {
      console.log(date, dateString);
      this.end_time = dateString;
    },
    save(value, key) {
      console.log(value);
      const newData = [...this.data];
      const newCacheData = [...this.cacheData];
      const target = newData.filter(item => key === item.key)[0];
      const targetCache = newCacheData.filter(item => key === item.key)[0];
      // target.editable = false;

      this.axios
        .post(
          "huiyuan/couponEdit.php",
          qs.stringify({
            id_num: value.id_num,
            price: value.price,
            start_time:
              this.start_time == "" ? value.start_time : this.start_time,
            end_time: this.end_time == "" ? value.end_time : this.end_time,
            limit_times: value.limit_times,
            full_price: value.full_price
          })
        )
        .then(res => {
          console.log(res);
          if (res.data.code == 303) {
            this.$notification["success"]({
              message: "成功",
              description: res.data.msg
            });
            this.getyhjlist(this.yhszpagination);
            if (target) {
              Object.assign(
                target,
                this.cacheData.filter(item => key === item.key)[0]
              );
              delete target.editable;
              this.data = newData;
            }
          } else {
            this.$notification["error"]({
              message: "失败",
              description: res.data.msg
            });
          }
        });
    },
    cancel(key) {
      const newData = [...this.data];
      const target = newData.filter(item => key === item.key)[0];
      if (target) {
        Object.assign(
          target,
          this.cacheData.filter(item => key === item.key)[0]
        );
        delete target.editable;
        this.data = newData;
      }
    },
    getyhjlist(pagination) {
      this.axios
        .post(
          "huiyuan/couponList.php",
          qs.stringify({
            page: pagination.current,
            pageSize: pagination.defaultPageSize,
            sqdwid: this.$store.state.bbl_sqdwid
          })
        )
        .then(res => {
          console.log(res);
          if (res.data.code == 303) {
            this.yhszpagination.total = Number(res.data.result.total);
            this.loading = false;
            this.cacheData = this.data.map(item => ({
              ...item
            }));
            this.data = res.data.result.data;
            for (var i = 0; i < this.data.length; i++) {
              this.data[i].key = this.data[i].id_num;
            }
          }
        });
    },
    addyhjsub() {
      console.log(this.price);
      console.log(this.full_price);
      console.log(this.limit_times);
      console.log(this.start_time);
      console.log(this.end_time);
      this.axios
        .post(
          "huiyuan/couponAdd.php",
          qs.stringify({
            sqdwid: this.$store.state.bbl_sqdwid,
            price: this.price,
            start_time: this.start_time,
            end_time: this.end_time,
            limit_times: this.limit_times,
            full_price: this.full_price
          })
        )
        .then(res => {
          console.log(res);
          if (res.data.code == 303) {
            this.$notification["success"]({
              message: "成功",
              description: res.data.msg
            });
            this.visible = false;
            this.getyhjlist(this.yhszpagination);
          } else {
            this.$notification["error"]({
              message: "失败",
              description: res.data.msg
            });
          }
        });
    },
    couponisOpen(value) {
      this.axios
        .post(
          "huiyuan/couponIsOpen.php",
          qs.stringify({
            id_num: value.id_num,
            is_open: value.is_open
          })
        )
        .then(res => {
          if (res.data.code == 303) {
            this.$notification["success"]({
              message: "成功",
              description: res.data.msg
            });
            this.getyhjlist(this.yhszpagination);
          } else {
            this.$notification["error"]({
              message: "失败",
              description: res.data.msg
            });
          }
        });
    },
    getyhjjgl(pagination) {
      this.axios
        .post(
          "huiyuan/couponAdminList.php",
          qs.stringify({
            page: pagination.current,
            pageSize: pagination.defaultPageSize,
            sqdwid: this.$store.state.bbl_sqdwid
          })
        )
        .then(res => {
          console.log(res);
          if (res.data.code == 303) {
            this.pagination.total = Number(res.data.result.total);
            this.loading = false;
            this.cacheData = this.data.map(item => ({
              ...item
            }));
            this.yhgldata = res.data.result.data;
            for (var i = 0; i < this.yhgldata.length; i++) {
              this.yhgldata[i].key = i;
            }
          }
        });
    }
  },

  created() {
    this.getyhjlist(this.yhszpagination);
    this.getyhjjgl(this.pagination);
  }
};
</script>

<style lang='less'>
.couponym {
  width: 98%;
  margin: 0 auto;
  position: relative;
  top: 66px;
  text-align: left;
  background-color: #fff;
  padding: 15px;
}
.ant-form-item {
  margin: 0 !important;
}
.ant-form-item-label {
  padding: 0 !important;
}
.colmar {
  margin: 10px 0;
}
.yhj_box {
  position: relative;
  display: inline-block;
  background: #e00000;
  color: #fff;
  //   padding: 5px 13px;
  font-size: 12px;
  border-radius: 6px;
  min-width: 141px;
  p {
    margin: 0;
    padding-top: 0;
  }
  .mj {
    font-size: 14px;
    padding: 6px 10px;
    border-bottom: 1px dotted #fff;
  }
}
.timeout{
      background: #ccc!important;
}
.yhj_box ::before {
  content: "";
  position: absolute;
  width: 15px;
  height: 15px;
  background: #fff;
  top: 50%;
  -webkit-transform: translateY(-50%);
  transform: translateY(-50%);
  left: -8px;
  border-radius: 50%;
}
.yhj_box ::after {
  content: "";
  position: absolute;
  width: 15px;
  height: 15px;
  background: #fff;
  top: 50%;
  -webkit-transform: translateY(-50%);
  transform: translateY(-50%);
  right: -8px;
  border-radius: 50%;
}
.yhsz_box {
  position: relative;
  .addyhj {
    position: absolute;
    top: -61px;
    right: 13px;
  }
}
</style>
